package com.ybwh.springboot2.util.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Set;

/**
 * excel按数量合并策略
 * @author wupo
 * @date 2022-03-30
 */
public class ExcelNumMergeStrategy  extends AbstractMergeStrategy {

    private List<Integer> kindNum;
    private Set<Integer> columns;
    private Sheet sheet;

    public ExcelNumMergeStrategy(List<Integer> kindNum, Set<Integer> columns) {
        this.kindNum = kindNum;
        this.columns = columns;
    }

    /**
     * 按照自定义得数量进行合并
     * @param index
     */
    private void mergeGroupColumn(Integer index) {
        Integer rowCnt = 1;
        for (Integer count : kindNum) {
            if(count != 1){
                CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCnt, rowCnt + count - 1, index, index);
                sheet.addMergedRegionUnsafe(cellRangeAddress);
            }
            rowCnt += count;
        }
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        if(CollectionUtils.isEmpty(kindNum)){
            return;
        }

        if (cell.getRowIndex() == 1) {
            if(columns.contains(cell.getColumnIndex())){
                this.mergeGroupColumn(cell.getColumnIndex());
            }
        }
    }

}
